package com.syqc.videos

import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.syqc.base.BaseTimeActivity
import com.syqc.choose.car.ChooseCarActivity
import com.syqc.choose.teamcar.TeamsCarsActivity
import com.syqc.comlib.custom.timer.CustomDatePicker
import com.syqc.comlib.custom.timer.DateFormatUtils
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.GsonUtil
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.startActivityTo
import com.syqc.entity.KeyValue
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityVideotapeBinding
import com.syqc.monitor.databinding.FragmentCarHistoryVideoBinding
import com.syqc.monitor.databinding.IncludeTabChangeBinding
import com.syqc.monitor.ui.newaddcar.KeyValuePopup
import com.syqc.adapter.ChooseTimeAdapter
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.TimeUtil
import com.syqc.utils.VideoHostUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/**
 *@Author Jasper
 *@Time   2020/12/4
 *@Desc   录像回放
 */
class VideotapeActivity :
    BaseTimeActivity<ActivityVideotapeBinding>(ActivityVideotapeBinding::inflate) {

    private val mViewModel by viewModels<CarHistoryVideoViewModel>()
    private val mKeyValuePopup: KeyValuePopup by lazy {
        KeyValuePopup(this)
    }
    private lateinit var mTabChangeVB: IncludeTabChangeBinding
    private lateinit var mCarVideoVB: FragmentCarHistoryVideoBinding
    override fun initView() {
        super.initView()
        mTabChangeVB = IncludeTabChangeBinding.bind(binding.root)
        mCarVideoVB = FragmentCarHistoryVideoBinding.bind(binding.root)
        VideoHostUtil.clearHostsClient()
        ToolbarHelper.setToolbar(this, R.string.title_monitor_history_video)
        mViewModel.videos = ""
        mViewModel.init(
            getString(R.string.desc_video_all_pass),
            getString(R.string.desc_video_pass)
        )
        setVideoView()
        handleModel()
        mCarVideoVB.lrvChooseCar.isVisible = true
        mKeyValuePopup.setCallBack(popupCallBack)
    }

    override fun setListener() {
        mTabChangeVB.rdbVideoTmn.setOnClickListener {
            mViewModel.isTmn = true
            mCarVideoVB.lrTvStream.isVisible = true
            mCarVideoVB.lrTvStorage.isVisible = true
            mCarVideoVB.lrTvRes.isVisible = true
        }
        mTabChangeVB.rdbVideoPlate.setOnClickListener {
            mViewModel.isTmn = false
            mCarVideoVB.lrTvStream.isVisible = false
            mCarVideoVB.lrTvStorage.isVisible = false
            mCarVideoVB.lrTvRes.isVisible = false
        }

        mCarVideoVB.lrvChooseCar.setOnClickListener {
            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsCarsActivity>(this) {
                    putExtra(Keys.INTENT_IS_VIDEO, true)
                }
            } else {
                launcher.launchAct<ChooseCarActivity>(this) {
                    putExtra(Keys.INTENT_IS_VIDEO, true)
                }
            }
        }

        mSureVB.tvSure.setOnClickListener {
            mViewModel.getTmVideosInfo(
                mTimeVB.lrvStartTime.getRightText(),
                mTimeVB.lrvEndTime.getRightText()
            )
        }
        mCarVideoVB.lrTvPass.setOnClickListener {
            mViewModel.popupType = 0
            mKeyValuePopup.showPopupWindow(
                window.decorView,
                getString(R.string.desc_video_passes),
                mViewModel.videoPassList,
                mViewModel.tmnPass
            )
        }
        mCarVideoVB.lrTvRes.setOnClickListener {
            mViewModel.popupType = 1
            mKeyValuePopup.showPopupWindow(
                window.decorView,
                getString(R.string.desc_video_res_type),
                DataUtil.getVideoRes(this),
                mViewModel.tmnRes
            )
        }
        mCarVideoVB.lrTvStream.setOnClickListener {
            mViewModel.popupType = 2
            mKeyValuePopup.showPopupWindow(
                window.decorView,
                getString(R.string.desc_video_stream_type),
                DataUtil.getVideoStream(this),
                mViewModel.tmnStream
            )
        }
        mCarVideoVB.lrTvStorage.setOnClickListener {
            mViewModel.popupType = 3
            mKeyValuePopup.showPopupWindow(
                window.decorView,
                getString(R.string.desc_video_storage_type),
                DataUtil.getVideoStorage(this),
                mViewModel.tmnStorage
            )
        }
        mTimeVB.lrvStartTime.rightClick {
            mViewModel.isStart = true
            mDatePicker.show(mTimeVB.lrvStartTime.getRightText())
        }
        mTimeVB.lrvEndTime.rightClick {
            mViewModel.isStart = false
            mDatePicker.show(mTimeVB.lrvEndTime.getRightText())
        }
    }


    /**
     * 资源设置
     */
    private val popupCallBack: KeyValuePopup.CallBack = object : KeyValuePopup.CallBack {
        override fun onBack(entity: KeyValue, index: Int) {
            when (mViewModel.popupType) {
                0 -> {
                    mViewModel.tmnPass = index
                    mViewModel.pass = entity.key
                    mCarVideoVB.lrTvPass.setRightText(entity.value)
                }

                1 -> {
                    mViewModel.tmnRes = index
                    mCarVideoVB.lrTvRes.setRightText(entity.value)
                }

                2 -> {
                    mViewModel.tmnStream = index
                    mCarVideoVB.lrTvStream.setRightText(entity.value)
                }

                3 -> {
                    mViewModel.tmnStorage = index
                    mCarVideoVB.lrTvStorage.setRightText(entity.value)
                }
            }
        }
    }

    private fun handleModel() {
        mViewModel.entitySub.hide().autoDispose(scopeProvider)
            .subscribe {
                startActivityTo<HistoryVideoInfoActivity>(this) {
                    putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                    putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                    putExtra("isTmn", mViewModel.isTmn)
                    if (mViewModel.pass == "0")
                        putExtra("passJson", GsonUtil.toJson(mViewModel.videoPassList))
                }
                LiveDataBus.get().with("key_history_video").postValue(it)
            }

        mViewModel.toastObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe(this::toastObserver)

        mRecyclerVB.recyclerWrap.layoutManager = GridLayoutManager(this, 4)
        mRecyclerVB.recyclerWrap.adapter = mAdapter.apply {
            setNewInstance(mViewModel.timeList)
            setOnItemClickListener { adapter, view, position ->
                index = position
                notifyDataSetChanged()
                mViewModel.chooseTime(position)
            }
        }
        mViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            mTimeVB.lrvStartTime.setRightText(it)
        }

        mViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            mTimeVB.lrvEndTime.setRightText(it)
        }
    }

    //*********************************时间选择相关*****************************************************
    private val mAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }
    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            this, callback, TimeUtil.normalDate, mViewModel.nowTimeFormat(), true
        ).apply {
            setCanShowPreciseTime(true)
        }
    }
    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, true)

            if (mViewModel.isStart) {
                mTimeVB.lrvStartTime.setRightText(time)
            } else {
                mTimeVB.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }

    private val launcher = registerResultOk { result ->
        result.data?.let {
            val carId = it.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
            val carName = it.getStringExtra(Keys.INTENT_CAR_NAME) ?: ""
            val videos = it.getStringExtra(Keys.VIDEO) ?: ""
            mCarVideoVB.lrvChooseCar.setRightText(carName)
            mViewModel.carId = carId
            mViewModel.videos = videos
            mViewModel.carName = carName
            setVideoView()
        }
    }


    private fun setVideoView() {
        mCarVideoVB.lrTvPass.setRightText(mViewModel.videoPassList[mViewModel.tmnPass].value)
        mCarVideoVB.lrTvRes.setRightText(DataUtil.getVideoRes(this)[mViewModel.tmnRes].value)
        mCarVideoVB.lrTvStream.setRightText(DataUtil.getVideoStream(this)[mViewModel.tmnStream].value)
        mCarVideoVB.lrTvStorage.setRightText(DataUtil.getVideoStorage(this)[mViewModel.tmnStorage].value)
    }
}